<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">


      <el-form-item label="驾驶证类型" prop="licenseType">
        <el-select v-model="queryParams.licenseType" placeholder="驾驶证类型" clearable>
          <el-option
            v-for="dict in dict.type.lg_driver_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="realName">
        <el-input
          v-model="queryParams.realName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input
          v-model="queryParams.age"
          placeholder="请输入年龄"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="家庭住址" prop="homeAddress">
        <el-input
          v-model="queryParams.homeAddress"
          placeholder="请输入家庭住址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="冷库名称" prop="coldName">
        <el-input
          v-model="queryParams.coldName"
          placeholder="请输入冷库名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="性别" clearable>
          <el-option
            v-for="dict in dict.type.lg_gender"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>

      </el-form-item>


      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable>
          <el-option
            v-for="dict in dict.type.lg_driver_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- 创建时间范围选择 -->
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['motor:driver:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['motor:driver:update']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['motor:driver:delete']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['motor:driver:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getDriverList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="driverList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="姓名" align="center" prop="realName" />
      <el-table-column label="头像" align="center" prop="avatar" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.avatar" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="冷库名称" align="center" prop="coldName" />
      <el-table-column label="年龄" align="center" prop="age" />

      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="驾驶证类型" align="center" prop="licenseType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.lg_driver_type" :value="scope.row.licenseType"/>
        </template>
      </el-table-column>
      <el-table-column label="家庭住址" align="center" prop="homeAddress" />

      <el-table-column label="性别" align="center" prop="gender">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.lg_gender" :value="scope.row.gender"/>
        </template>
      </el-table-column>


      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.lg_driver_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['motor:driver:update']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['motor:driver:delete']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getTotalSome"
    />



    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form :inline="true" :model="form" label-width="100px">
          <el-form-item label="姓名" prop="realName">
            <el-input v-model="form.realName" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input v-model="form.age" placeholder="请输入年龄" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱" />
          </el-form-item>
        </el-form>

        <el-form :inline="true" :model="form" label-width="100px">
        <el-form-item label="账号" prop="account">
          <el-input v-model="form.account" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" type="password" maxlength="20" show-password />
        </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号" />
          </el-form-item>
        </el-form>


        <el-form :inline="true" :model="form" label-width="100px">
        <el-form-item label="身份证号" prop="idNumber ">
          <el-input v-model="form.idNumber " placeholder="请输入身份证号" />
        </el-form-item>
          <el-form-item label="驾驶证类型" prop="licenseType">
            <el-radio-group v-model="form.licenseType">
              <el-radio
                v-for="dict in dict.type.lg_driver_type"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>

        <el-form-item label="家庭住址" prop="homeAddress">
          <el-input v-model="form.homeAddress" placeholder="请输入家庭住址" />
        </el-form-item>
        </el-form>
        <el-form :inline="true" :model="form" label-width="100px">
          <el-form-item label="绑定冷库">
            <el-button type="primary" @click="openColdStoreDialog">
              {{ form.coldName || '选择冷库' }}
            </el-button>
<!--            <span v-if="form.coldName">{{ form.coldName }}</span>-->
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form.gender">
              <el-radio
                v-for="dict in dict.type.lg_gender"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in dict.type.lg_driver_status"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>

        <el-form :inline="true" :model="form" label-width="180px">

        <el-form-item label="身份证正面照片" prop="frontImage">
          <image-upload v-model="form.frontImage"/>
        </el-form-item>
        <el-form-item label="身份证反面照片" prop="backImage">
          <image-upload v-model="form.backImage"/>
        </el-form-item>
        </el-form>
        <el-form :inline="true" :model="form" label-width="180px">
        <el-form-item label="头像" prop="avatar">
          <image-upload v-model="form.avatar"/>
        </el-form-item>
        <el-form-item label="驾驶证照片" prop="licenseImage">
          <image-upload v-model="form.licenseImage"/>
        </el-form-item>
        </el-form>


        <el-dialog
          title="选择冷库"
          :visible.sync="coldStoreDialogVisible"
          :modal="false"
          width="600px"
          @close="cancelColdStoreSelection"
        >
          <el-table :data="coldList" style="width: 100%">
            <el-table-column
              prop="coldName"
              label="冷库名称"
              width="150"
            />
            <el-table-column
              prop="coldDescript"
              label="描述"
              width="150"
            />
            <el-table-column
              prop="address"
              label="地址"
              width="150"
            />
<!--            <el-table-column-->
<!--              prop="coordinateX"-->
<!--              label="X坐标"-->
<!--              width="150"-->
<!--            />-->
<!--            <el-table-column-->
<!--              prop="coordinateY"-->
<!--              label="Y坐标"-->
<!--              width="150"-->
<!--            />-->
<!--            <el-table-column-->
<!--              prop="area"-->
<!--              label="占地面积"-->
<!--              width="150"-->
<!--            />-->
<!--            <el-table-column-->
<!--              prop="totalVolume"-->
<!--              label="总容积"-->
<!--              width="150"-->
<!--            />-->
<!--            <el-table-column-->
<!--              prop="remainingVolume"-->
<!--              label="剩余容积"-->
<!--              width="150"-->
<!--            />-->


            <el-table-column
              label="操作"
              width="100"
              align="center"
            >
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="selectColdStore(scope.row)"
                >选择</el-button> <!-- 点击按钮时选择冷库 -->
              </template>
            </el-table-column>
          </el-table>

          <div slot="footer" class="dialog-footer">
            <el-button @click="cancelColdStoreSelection">取 消</el-button>
          </div>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="totalList.pageNum"
            :limit.sync="totalList.pageSize"
            @pagination="getTotalCold"
          />
        </el-dialog>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="'司机详情'" :visible.sync="detailVisible" width="600px" append-to-body>
      <el-form :model="detailForm" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="姓名">{{ detailForm.realName }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用户名">{{ detailForm.username }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年龄">{{ detailForm.age }}</el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="8">
            <el-form-item label="手机号">{{ detailForm.phone }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证号">{{ detailForm.idNumber }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别">
              <dict-tag :options="dict.type.lg_gender" :value="detailForm.gender"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="司机状态">
              <dict-tag :options="dict.type.lg_driver_status" :value="detailForm.status"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="家庭住址">{{ detailForm.homeAddress }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="冷库名称">{{ detailForm.coldName }}</el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="驾驶证类型">{{ detailForm.licenseType }}</el-form-item>
        <el-form-item label="驾驶证照片">
          <img v-if="detailForm.licenseImage" :src="detailForm.licenseImage" alt="驾驶证" style="width: 350px;"/>
        </el-form-item>

        <el-form-item label="头像">
          <img v-if="detailForm.avatar" :src="detailForm.avatar" alt="头像" style="width: 50px; height: 100px;"/>
        </el-form-item>
        <el-form-item label="身份证正面照片">
          <img v-if="detailForm.frontImage" :src="detailForm.frontImage" alt="身份证正面" style="width: 200px;"/>
        </el-form-item>
        <el-form-item label="身份证反面照片">
          <img v-if="detailForm.backImage" :src="detailForm.backImage" alt="身份证反面" style="width: 200px;"/>
        </el-form-item>

        <el-form-item label="创建时间">{{ parseTime(detailForm.createTime) }}</el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import {
  listDriver,
  getTotal,
  delDriver,
  addDriver,
  updateDriver,
  listCold,
  getCount,
  getDriverById
} from "@/api/motor/driver";
import store from "@/store";


export default {
  name: "Driver",
  dicts: ['lg_gender','lg_driver_status','lg_driver_type'],
  data() {
    return {
      userId:store.state.user.id, //将缓存的用户id赋值给userId
      userName:store.state.user.name, //将缓存的用户id赋值给userId
      // 遮罩层
      loading: true,
      coldStoreDialogVisible: false,  // 控制冷库选择框显示
      selectedColdStore: null,
      detailVisible: false,
      detailForm: {},
      // 存储选择的冷库
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 日期范围
      dateRange: [],

      driverColdList: [],
      //冷库信息
      coldList: [],
      totalList:{
        pageNum: 1,
        pageSize:10},
      // 司机表格数据
      driverList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        realName: undefined,
        username: undefined,
        gender: undefined,
        account: undefined,
        password: undefined,
        email: undefined,
        phone: undefined,
        idNumber: undefined,
        frontImage: undefined,
        backImage: undefined,
        homeAddress: undefined,
        licenseType: undefined,
        licenseImage: undefined,
        coldId: undefined,
        coldName: undefined,
        age: undefined,
        beginTime: undefined,
        endTime: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        realName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" }
        ],
        idNumber: [
          { required: true, message: "身份证号不能为空", trigger: "blur" }
        ],
        age: [
          { required: true, message: "年龄不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getDriverList();
    this.getTotalSome();
    this.getListSome();
    this.getTotalCold();
    // this.handleDetail();
  },
  methods: {
    handleDetail(row) {
      const driverId = row.driverId;
      getDriverById(driverId).then(response => {
        this.form = response.data;
        // 查找冷库名称并赋值给 form.coldName
        const coldStore = this.coldList.find(cold => cold.coldId === response.data.coldId);
        if (coldStore) {
          this.form.coldName = coldStore.coldName;  // 更新冷库名称
        }
        // 为 detailForm 赋值
        this.detailForm = { ...this.form };
        console.log(this.detailForm); // 打印 detailForm 确认数据
        this.detailVisible = true;
        this.title = "修改司机信息";
      });
    },



    /** 查询冷库名单 */
    // getListSome() {
    //   listCold({
    //     pageNum: this.totalList.pageNum,
    //     pageSize: this.totalList.pageSize,
    //   }).then(response => {
    //     this.coldList = response.data;
    //
    //   });
    // },
    /** 查询冷库名单 */
    getListSome() {
      return new Promise((resolve, reject) => {
        listCold({
          pageNum: this.totalList.pageNum,
          pageSize: this.totalList.pageSize,
        }).then(response => {
          this.coldList = response.data;
          resolve(); // 加载完成后 resolve
        }).catch(error => {
          reject(error);
        });
      });
    },

    /** 查询司机列表 */
    getDriverList() {
      this.loading = true;
      this.queryParams.beginTime = this.dateRange[0];
      this.queryParams.endTime = this.dateRange[1];
      listDriver(this.queryParams).then(response => {
        this.driverList = response.data;
        this.loading = false;
      });
      this.loading = false;
    },
    //获取司机数据总条数
    getTotalSome() {
      this.loading = true;
      getTotal(this.queryParams).then(response => {
        this.getDriverList();
        this.total = response.data;
        this.loading = false;
      });
      this.loading = false;
    },
    //获取冷库数据总条数
    getTotalCold() {
      this.loading = true;
      getCount(this.queryParams).then(response => {
        this.getListSome();
        this.total = response.data;
        this.loading = false;
      });
      this.loading = false;
    },

    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {

        status: "0",
        gender: "1",
        licenseType: "1",
        beginTime: undefined,
        endTime: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
       this.getTotalSome();

    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.driverId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.getListSome();
      this.title = "添加司机";
    },
    /** 修改按钮操作 */
    // handleUpdate(row) {
    //   this.getListSome();  // 获取冷库列表
    //   this.reset();
    //   const driverId = row.driverId || this.ids;
    //   getDriverById(driverId).then(response => {
    //     this.form = response.data;
    //     this.form.gender = response.data.gender.toString();
    //     this.form.status = response.data.status.toString();
    //     // 查找冷库名称并赋值给 form.coldName
    //     const coldStore = this.coldList.find(cold => cold.coldId === response.data.coldId);
    //     if (coldStore) {
    //       this.form.coldName = coldStore.coldName;  // 更新冷库名称
    //       this.form.coldId = response.data.coldId;  // 保证冷库ID也更新
    //     }
    //
    //     this.open = true;
    //     this.title = "修改司机信息";
    //   });
    // },
    handleUpdate(row) {
      this.reset();
      const driverId = row.driverId || this.ids;
      // 先获取冷库列表
      this.getListSome().then(() => {
        // 获取司机详情
        getDriverById(driverId).then(response => {
          this.form = response.data;
          this.form.gender = response.data.gender.toString();
          this.form.status = response.data.status.toString();
          this.form.licenseType = response.data.licenseType.toString();
          // 根据 coldId 查找对应的冷库名称
          const coldStore = this.coldList.find(cold => cold.coldId === response.data.coldId);
          if (coldStore) {
            this.form.coldName = coldStore.coldName; // 更新冷库名称
          }
          // 将表单数据赋值给 detailForm
          this.detailForm = { ...this.form };
          this.open = true;
          this.title = "修改司机信息";
        });
      });
    },




    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.driverId != undefined) {
            // 添加修改人
            this.form.updateBy = this.userName;
            updateDriver(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getDriverList();
            });
          } else {
            //添加创建人
            this.form.createBy = this.userName;
            addDriver(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getDriverList();
              this.form = {};

            });
          }
        }
      });
    },

    /** 删除按钮操作 */

    handleDelete(row) {
      const driverIds = row.driverId || this.ids;
      this.$modal.confirm('是否确认删除此数据项？').then(function() {
        return delDriver(driverIds);  // 使用 DELETE 请求
      }).then(() => {
        this.getDriverList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});

    },
    // 显示冷库选择对话框
    openColdStoreDialog() {
      this.coldStoreDialogVisible = true;
      this.getListSome();  // 获取冷库列表
      this.getTotalCold();
    },
    // 选择冷库
    selectColdStore(coldStore) {
      this.selectedColdStore = coldStore;  // 保存选中的冷库
      this.form.coldName = coldStore.coldName;  // 更新表单中的冷库名称
      this.form.coldId = coldStore.coldId;  // 更新表单中的冷库ID
      this.coldStoreDialogVisible = false;  // 关闭冷库选择对话框
    },

    // 取消选择
    cancelColdStoreSelection() {
      this.coldStoreDialogVisible = false;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('motor/driver/export', {
        ...this.queryParams
      }, `driver_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
